<?php

namespace App\Controller;

use Lcobucci\JWT\Signer\Hmac\Sha256;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Lcobucci\JWT\Builder;

class TokenController extends Controller
{
    const SING_CHECK_CODE_KEY = "94685c89012e79840b326884cf708c61";//用于校验码的生成;

    /**
     * 获取token
     * @param Request $request
     * @Route("/get/token", name="get_token")
     */
    public function createToken(Request $request)
    {
        $username = $request->get("username", '');
        $password = $request->get("password", "");
        if (empty($username) || empty($password)) {
            return new JsonResponse(array("code" => 400, "message" => "参数不全"));
        }
        if (empty($userData = $this->get('common_user')->getUser($username, $password)) && empty($userData = $this->get('common_admin')->getUser($username, $password))) {
            return new JsonResponse(array("code" => 401, "message" => "账号或密码不正确"));
        }
        //颁发token
        $signer = new Sha256();
        $token = (new Builder())->setIssuer('http://symfony4.cn') // Configures the issuer (iss claim)
            ->setAudience('http://symfony4.cn') // Configures the audience (aud claim)
            ->setId(1, true) // Configures the id (jti claim), replicating as a header item
            ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
            ->setNotBefore(time() + 60) // Configures the time that the token can be used (nbf claim)
            ->setExpiration(time() + 3600) // Configures the expiration time of the token (exp claim)
            ->set('uid', 1) // Configures a new claim, called "uid"
            ->set('role', $userData['role'])
            ->set('user_id', $userData['user_id'])
            ->set('username', $username)
            ->sign($signer, $this::SING_CHECK_CODE_KEY)
            ->getToken(); // Retrieves the generated token

        return new JsonResponse(array('token' => (string) $token));
    }
}